package cn.com.nes.common.util;


import org.apache.commons.lang.StringUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParamUtil {

    /**
     * 统一返回yyyy-MM-dd HH:mm:ss格式
     * 为空时返回当前时间从0点开始
     *
     * @param startTime
     * @return
     */
    public static String handleStartTime(String startTime) {
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String result;
        if (StringUtils.isEmpty(startTime)) {
            result = yyyyMMdd.format(new Date()) + " 00:00:00";
        } else {
            if (startTime.trim().matches("^(\\d{1,4})(-|\\/)(\\d{1,2})\\2(\\d{1,2})$")) {
                try {
                    result = yyyyMMdd.format(yyyyMMdd.parse(startTime)) + " 00:00:00";
                } catch (ParseException e) {
                    result = startTime;
                }
            } else {
                try {
                    result = yyyyMMddHHmmss.format(yyyyMMddHHmmss.parse(startTime));
                } catch (ParseException e) {
                    result = startTime;
                }
            }
        }
        return result;
    }

    /**
     * 统一返回yyyy-MM-dd HH:mm:ss格式
     * 为空时返回当前时间从23:59:59点开始
     *
     * @param endTime
     * @return
     */
    public static String handleEndTime(String endTime) {
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String result;
        if (StringUtils.isEmpty(endTime)) {
            String topDayDate = DateContUtil.getTopDayDate(-1, yyyyMMdd.format(new Date()));
            result = topDayDate + " 23:59:59";
        } else {
            if (endTime.trim().matches("^(\\d{1,4})(-|\\/)(\\d{1,2})\\2(\\d{1,2})$")) {
                try {
                    result = yyyyMMdd.format(yyyyMMdd.parse(endTime)) + " 23:59:59";
                } catch (ParseException e) {
                    result = endTime;
                }
            } else {
                try {
                    result = yyyyMMddHHmmss.format(yyyyMMddHHmmss.parse(endTime));
                } catch (ParseException e) {
                    result = endTime;
                }
            }
        }
        return result;
    }

    public static String formatHourTime(Double doubleValue) {
        NumberFormat format = new DecimalFormat("00");
        if(doubleValue == null) {
            return "00:00:00";
        }
        int value = (int)(doubleValue * 3600);
        int hour = value / 3600;
        value = value - hour * 3600;
        int minute = value / 60;
        value = value - minute * 60;
        int second = value;

        return format.format(hour) + ":" + format.format(minute) + ":" + format.format(second);
    }

}
